//
//  ChangeURLVC.m
//  ProjectforHDX
//
//  Created by Jaesun on 16/6/30.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "ChangeURLVC.h"
#import "ScrollViewLabelCell.h"

@interface ChangeURLVC ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate> {
    
    NSMutableArray *severURLArr;
}
/**
 *  更换URL的title
 */
@property (nonatomic, strong) UILabel *changeURLTitleLabel;
/**
 *  URL输入视图
 */
@property (nonatomic, strong) UIView *URLInputView;
/**
 *  URL 输入框
 */
@property (nonatomic, strong) UITextField *URLTextField;
/**
 *  弹出收起下拉菜单按钮
 */
@property (nonatomic, strong) UIButton *dropMenuBtn;
/**
 *  增加URL按钮
 */
@property (nonatomic, strong) UIButton *addURLBtn;
/**
 *  弹出下拉菜单
 */
@property (nonatomic, strong) UITableView *URLTableView;

@property (nonatomic, strong) UILabel *httpServerLabel;


@end

static NSString *Cell_ID = @"uITableViewCell";

static NSString *ID_ScrollViewLabelCell = @"scrollViewLabelCell";

@implementation ChangeURLVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化数据
    [self setupDatas];
    // 初始化视图
    [self setupViews];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark 数据初始化
- (void)setupDatas {
    
    
    self.URLTextField.text = [THMangerTool getUsedHost];
    
    
    NSMutableArray *hostArr = [THMangerTool getHostList];
    NSLog(@"hostArr.cout is --%lu",(unsigned long)hostArr.count);
    severURLArr = [NSMutableArray arrayWithArray:hostArr];

}

#pragma mark 视图初始化
- (void)setupViews {
    
    self.mBackColor = [THMangerTool getRZColor:230 green:230 blue:230 alpha:1];
    
    // navigationController
    self.navigationController.navigationBar.hidden = NO;
    self.navColor =  SYSTEM_COLOR;
    
    // changeURLTitleLabel
    self.changeURLTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, SCREEN_WIDTH - 30, 40)];
    self.changeURLTitleLabel.backgroundColor = [UIColor clearColor];
    self.changeURLTitleLabel.text = [UtilCheck language:@"changeURL.changeServer"];
    [self.view addSubview:self.changeURLTitleLabel];
    
    // URLInputVeiw
    self.URLInputView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.changeURLTitleLabel.frame), SCREEN_WIDTH, 44)];
    self.URLInputView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.URLInputView];
    
    // URLTextField
    self.URLTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 2, SCREEN_WIDTH - 105, 40)];
    _URLTextField.text = [THMangerTool getUsedHost];
    self.URLTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.URLInputView addSubview:self.URLTextField];
    
    // dropMenuBtn
    self.dropMenuBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.dropMenuBtn.frame = CGRectMake(CGRectGetMaxX(self.URLTextField.frame), CGRectGetMinY(self.URLTextField.frame), 40, 40);
    [self.dropMenuBtn setImage:BDFILEIMAGENAEM(@"Login/btn_close") forState:(UIControlStateNormal)];
    [self.dropMenuBtn addTarget:self action:@selector(touchDropMenuBtn:) forControlEvents:
     (UIControlEventTouchUpInside)];
    [self.URLInputView addSubview:self.dropMenuBtn];
    
    // addURLBtn
    self.addURLBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.addURLBtn.frame = CGRectMake(CGRectGetMaxX(self.dropMenuBtn.frame) + 5, CGRectGetMinY(self.dropMenuBtn.frame), 40, 40);
    [self.addURLBtn setImage:BDFILEIMAGENAEM(@"Login/btn_add") forState:(UIControlStateNormal)];
    [self.addURLBtn addTarget:self action:@selector(touchAddURLBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.URLInputView addSubview:self.addURLBtn];
    
    // URLTableView
    [self setupURLTableViewWithURLCount:0];
}


/**
 *  初始化URLTableView
 */
- (void)setupURLTableViewWithURLCount:(NSInteger )count {
    
    if (!self.URLTableView) {
       
        self.URLTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.URLInputView.frame) + 1, SCREEN_WIDTH, count * 44) style:(UITableViewStylePlain)];
        self.URLTableView.delegate = self;
        self.URLTableView.dataSource = self;
        
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectHttpServer:)];
        [headView addGestureRecognizer:gesture];
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH - 110, 44)];
        NSString *text = [THMangerTool getRecommendHost];
        CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, 44) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
        self.httpServerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, 44)];
        self.httpServerLabel.text = [THMangerTool getRecommendHost];
        scrollView.contentSize = self.httpServerLabel.frame.size;
        [scrollView addSubview:self.httpServerLabel];
        [headView addSubview:scrollView];
       
        UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(headView.right - 90, 0, 85, 44)];
        stateLabel.font= [UIFont systemFontOfSize:12];
        stateLabel.textAlignment = NSTextAlignmentCenter;
        stateLabel.text = [NSString stringWithFormat:@"(%@)",[UtilCheck language:@"changeURL.SYSRecommend"]];
        [headView addSubview:stateLabel];

        self.URLTableView.tableHeaderView = headView;
       
        //[self.URLTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:Cell_ID];
       
        [self.URLTableView registerClass:[ScrollViewLabelCell class] forCellReuseIdentifier:ID_ScrollViewLabelCell];
        
        [self.view addSubview:self.URLTableView];
    }
    else {
        self.URLTableView.frame = CGRectMake(0, CGRectGetMaxY(self.URLInputView.frame) + 1, SCREEN_WIDTH, count * 44);
    }
}

#pragma mark- UITableViewDelegate DataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return severURLArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ScrollViewLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:ID_ScrollViewLabelCell forIndexPath:indexPath];
   
    cell.title = severURLArr[indexPath.row];

    NSString *usedHost = [THMangerTool getUsedHost];
   
    if([severURLArr[indexPath.row] isEqualToString:usedHost]){
        //显示勾选按钮
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        
       cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BOOL isChanged = [THMangerTool setUserHost:severURLArr[indexPath.row]];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isDefaultHost"];

    if (isChanged) {
        [Toolobject showTextWithMessage:[UtilCheck language:@"changeURL.changedOK"]];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [severURLArr removeObjectAtIndex:indexPath.row];
        [THMangerTool deleteHostAtIndex:indexPath.row];
        [self setupURLTableViewWithURLCount:severURLArr.count + 1];
        [self.URLTableView reloadData];
    }
}

#pragma mark- 其他事件
- (void)touchDropMenuBtn:(UIButton *)sender {
    if (!self.URLTableView) {
        [self setupURLTableViewWithURLCount:severURLArr.count + 1];
    }
    CGRect  frame = self.URLTableView.frame;
    NSInteger count = severURLArr.count;
    CGFloat height = count * 44 + 44;
    if (frame.size.height > 0) {
        [self.dropMenuBtn setImage:BDFILEIMAGENAEM(@"Login/btn_close") forState:(UIControlStateNormal)];
        [UIView animateWithDuration:0.6 animations:^{
            self.URLTableView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 0);
        }];
    }
    
    if (frame.size.height <= 0) {
        [self.dropMenuBtn setImage:BDFILEIMAGENAEM(@"Login/btn_open") forState:(UIControlStateNormal)];
        [UIView animateWithDuration:0.6 animations:^{
            self.URLTableView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
        }];
    }
}

/**
 *  添加URL按钮点击事件
 *
 *  @param sender
 */
- (void)touchAddURLBtn:(UIButton *)sender {
    
    [self.URLTextField resignFirstResponder];
    
    if (![self.URLTextField.text hasPrefix:@"http://"]) {
        [[BDHUD sharedManager] showWords:[UtilCheck language:@"changeURL.perfectURL"]]; // 请输入合法的URL
        return;
    }
    
    BOOL isNewURL = [THMangerTool addHost:self.URLTextField.text];
    
    if (isNewURL) {
        [Toolobject showTextWithMessage:[UtilCheck language:@"changeURL.addURLOK"]]; // 添加成功
        [severURLArr addObject:self.URLTextField.text];
    [self setupURLTableViewWithURLCount:severURLArr.count + 1];
        [self.URLTableView reloadData];
    }
    else {
        [[BDHUD sharedManager] showWords:[UtilCheck language:@"changeURL.exsitURL"]]; // 已存在服务器地址
    }
}

- (void)selectHttpServer:(UITapGestureRecognizer *)sender {
    
    [Toolobject showTextWithMessage:[UtilCheck language:@"changeURL.changedOK"]];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_SERVER];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:IS_USER_SElELECTED];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
